#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file: info.py
@time: 2024-07-07 20:00
@desc: 
"""
import traceback

from flask import Blueprint, request, jsonify, Response
from common_tools import apply_formatting
from global_scope import get_db, images_sheet_name, boxs_sheet_name, box_tags_sheet_name, box_types_sheet_name, \
    contacts_sheet_name, field_stacks_sheet_name, areas_sheet_name, configuration_sheet_name
from tools import log_operations, token_required, get_boxs_df, get_area_df, get_field_stack_df, get_contacts_df, \
    get_box_types_df, get_box_tags_df, clear_all_infos, excel_to_box_tags, excel_to_box_types, excel_to_contacts, \
    excel_to_field_stacks, excel_to_areas, excel_to_boxs
from tools import get_configurations_df, excel_to_configurations
from tools import get_images_df, excel_to_images
from tools import get_configuration
from io import BytesIO
from flask import send_file
import pandas as pd
from tools import get_ips_df, excel_to_ips, get_leads_df, excel_to_leads
from global_scope import leads_sheet_name, ips_sheet_name

db = get_db()
info_bp = Blueprint('info', __name__, url_prefix='/infos')


@info_bp.route('/upload', methods=['POST'])
@log_operations
@token_required
def upload_all_infos():
    if 'file' not in request.files:
        return jsonify({"code": 1, "message": "No file part"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"code": 1, "message": "No selected file"}), 400

    try:
        excel_to_ips(file, request)
        excel_to_leads(file, request)
        excel_to_images(file, request)
        excel_to_box_tags(file, request)
        excel_to_box_types(file, request)
        excel_to_contacts(file, request)
        excel_to_field_stacks(file, request)
        excel_to_areas(file, request)
        excel_to_boxs(file, request)
        excel_to_configurations(file, request)
        return jsonify({
            "code": 0,
            "message": f"allInfo uploaded successfully"
        }), 201
    except Exception as e:
        tb = traceback.format_exc()
        request.trace_logger.error(f"Exception occurred: {str(e)}\n{tb}")
        return jsonify({"code": 1, "message": str(e)}), 500


def download_action():
    output = BytesIO()
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        df_objs = [
            (get_boxs_df(), boxs_sheet_name),
            (get_images_df(), images_sheet_name),
            (get_box_tags_df(), box_tags_sheet_name),
            (get_box_types_df(), box_types_sheet_name),
            (get_contacts_df(), contacts_sheet_name),
            (get_field_stack_df(), field_stacks_sheet_name),
            (get_area_df(), areas_sheet_name),
            (get_configurations_df(), configuration_sheet_name),
            (get_ips_df(), ips_sheet_name),
            (get_leads_df(), leads_sheet_name)
        ]
        # 写入数据
        for df, sheet_name in df_objs:
            df.to_excel(writer, index=False, sheet_name=sheet_name)
            apply_formatting(writer.sheets[sheet_name], df)

    output.seek(0)
    return output


@info_bp.route('/download', methods=['GET'])
@log_operations
@token_required
def download_all_infos():
    output = download_action()
    return send_file(output, download_name="all_info_output.xlsx", as_attachment=True)


@info_bp.route('/clear', methods=['GET'])
@log_operations
@token_required
def clear_all():
    clear_all_infos(request)

    return jsonify({
        "code": 0,
        "message": f"Clear info successfully"
    }), 201


@info_bp.route('/home', methods=['GET'])
@log_operations
@token_required
def get_home_info() -> tuple[Response, int]:
    return jsonify({
        "code": 0,
        "message": "get home info successfully",
        "data": {
            "FamousQuotes": get_configuration("FamousQuotes", request),
            "CompanyIntroduction": get_configuration("CompanyIntroduction", request),
            "Image": get_configuration("Image", request),
            "CompanyName": get_configuration("CompanyName", request),
            "QuotesAuthor": get_configuration("QuotesAuthor", request)
        }
    }), 201
